package com.tg.app.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.appbase.custom.constant.CommonConstants;
import com.tg.app.R;
import com.tg.app.widget.BottomSheetListDialog;
import com.tg.app.widget.ZoomPanTextureView;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.media.DefaultVideoDecoder;
import com.tg.data.media.OnMediaPlayListener;


public abstract class CameraPlayerPiPView extends CameraPlayerView {
    private static final String TAG = "CameraPlayerPiPView";
    protected Button mPipVideoBtn;
    protected View mSwitchVideoBtn;
    protected ZoomPanTextureView textureViewMini;
    protected DefaultVideoDecoder mediaSyncMini;

    protected int nMiniCodecId = 0;
    protected boolean isCloudPipVideo = false;
    protected boolean isSdCardPipVideo = false;
    protected boolean isMiniVideoOpen = true;
    protected  boolean isOpenOverlap = true;
    protected  OnCameraPlayerPiPViewListener onCameraPlayerListener;
    protected OnMediaPlayListener onMiniPlayListener;
    protected View mFloatView;



    public DefaultVideoDecoder getMediaSyncMini() {
        return mediaSyncMini;
    }

    public void setOnCameraPlayerListener(OnCameraPlayerPiPViewListener onCameraPlayerListener) {
        this.onCameraPlayerListener = onCameraPlayerListener;
    }

    public void setOpenOverlap(boolean openOverlap) {
        isOpenOverlap = openOverlap;
    }

    public CameraPlayerPiPView(Context context) {
        super(context);
    }

    public CameraPlayerPiPView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CameraPlayerPiPView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        View view = LayoutInflater.from(context).inflate(getLayoutID(), this);
        initView(view);
        textureView = view.findViewById(R.id.camera_player_pip_view);
        textureViewMini = view.findViewById(R.id.camera_player_pip_view_mini);
        mediaSyncMini = new DefaultVideoDecoder();
        setListener();

    }

    protected abstract void initView(View view);

    @Override
    public void setListener() {
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {

                if (width == 0 || height == 0) return;
                mediaSync.initMediaSync(textureView, nCodecId);
                mediaSync.setPlayType(getMediaType());
                if (isMainPlayer()) {
                    setVideoSize(textureView,width, height);
                    textureUpdatedReset();
                } else {
                    textureView.setVideoSize(width, height);
                }
                audioDecoder.start();

            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                TGLog.d(TAG,"onSurfaceTextureSizeChanged textureView width:"+width +" height:"+height);
                if (width == 0 || height == 0) return;
                if (isMainPlayer()) {
                    setVideoSize(textureView,width, height);
                } else if (!isPlayLive){
                    textureView.setVideoSize(width, height);
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                isSurfaceTextureUpdated = false;
                mediaSync.stop();
                audioDecoder.stop();
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {
                if (isMainPlayer()) {
                    textureUpdated();
                }
            }
        });
        textureViewMini.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                mediaSyncMini.initMediaSync(textureViewMini, nMiniCodecId);
                mediaSyncMini.setPlayType(getMediaType());
                if (isMainPlayer()) {
                    textureViewMini.setVideoSize(width, height);
                } else {
                    setVideoSize(textureViewMini,width, height);
                    textureUpdatedReset();
                }
                audioDecoder.start();
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                TGLog.d(TAG, "onSurfaceTextureSizeChanged textureViewMini width:"+width +" height:"+height);
                if (isMainPlayer()&&!isPlayLive) {
                    textureViewMini.setVideoSize(width, height);
                } else {
                    setVideoSize(textureViewMini,width, height);
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                isSurfaceTextureUpdated = false;
                mediaSyncMini.stop();
                audioDecoder.stop();
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {
                if (!isMainPlayer()) {
                    textureUpdated();
                }
            }
        });
        onMiniPlayListener = new OnMediaPlayListener() {
            @Override
            public void onMediaPlayFirstTimestamp(long pts) {

            }

            @Override
            public void onMediaPlayChanged(boolean isStart) {

            }

            @Override
            public void onMediaPlayUpdated(long pts) {

                if (onMediaPlayListener!=null){
                    onMediaPlayListener.onMediaPlayUpdated(0);
                }
            }

            @Override
            public void onMediaCloudPlayUpdated(long pts) {

            }

        };
    }

    @Override
    public void setLiveViewShow(boolean playLive) {
        super.setLiveViewShow(playLive);
        if (isVertical()){
            setPipBtnVisibility(GONE);
        }else if (isLivePlayType()||isCloudPipVideo||isSdCardPipVideo){
            setPipBtnVisibility(VISIBLE);
        }
    }

    public void setPipBtnVisibility(int visibility){
        setPipBtnVisibilityAnimation(visibility);
    }

    @Override
    public void setAnchorView(View view) {
        FrameLayout layout = view.findViewById(R.id.camera_player_control_layout);
        View controlView = LayoutInflater.from(mContext).inflate(R.layout.layout_camera_player_pip_overlap_control, layout);
        mSwitchVideoBtn = controlView.findViewById(R.id.btn_player_view_pip_switch);

    }

    @Override
    public void setFloatView(View view) {
        mFloatView = view;
        mPipVideoBtn = view.findViewById(R.id.rb_video_mini);
        initMiniVideoOpen();
    }

    @Override
    protected float getAspectRatio() {
        float ratio = super.getAspectRatio();
        if (isMainPlayer()) {
            if (mediaSync.getAlignWidth() > 0 && mediaSync.getAlignHight() > 0) {
                ratio = mediaSync.getAlignWidth() * 1.0f / mediaSync.getAlignHight();
            }
        } else {
            if (mediaSyncMini.getAlignWidth() > 0 && mediaSyncMini.getAlignHight() > 0) {
                ratio = mediaSyncMini.getAlignWidth() * 1.0f / mediaSyncMini.getAlignHight();
            }
        }
        return ratio;
    }

    @Override
    public void mediaSyncStart() {
        super.mediaSyncStart();
        mediaSyncMini.start();
    }

    @Override
    public void mediaSyncClear() {
        super.mediaSyncClear();
        mediaSyncMini.clear();
    }

    @Override
    public void recordStart() {

        if (isMainPlayer()) {
            super.recordStart();
            return;
        }
        mediaSyncMini.recordStart();
        isRecording = true;
    }

    @Override
    public void recordEnd() {
        if (isMainPlayer()) {
            super.recordEnd();
            return;
        }
        mediaSyncMini.recordEnd(mContext);
        isRecording = false;
    }


    @Override
    public void setSpeed(int speed) {
        super.setSpeed(speed);
        mediaSyncMini.setSpeed(speed);
    }

    @Override
    public Bitmap getTextureViewBmp() {
        if (isMainPlayer()) {
            return super.getTextureViewBmp();
        }
        return getTextureViewBmp(mediaSyncMini,textureViewMini);
    }

    @Override
    protected void updateListener() {
        mediaSyncMini.setResetListener(resetListener);
        mediaSync.setResetListener(resetListener);
        if (isMainPlayer()){
            mediaSync.setOnScreencapListener(onScreencapListener);
            mediaSync.setPlayListener(onMediaPlayListener);
            textureView.setOnPtzControlTouchListener(ptzControlTouchListener);
            textureViewMini.setOnPtzControlTouchListener(null);
            mediaSyncMini.setPlayListener(onMiniPlayListener);
            mediaSyncMini.setResetListener(resetListener);
        }else {
            mediaSyncMini.setOnScreencapListener(onScreencapListener);
            mediaSyncMini.setPlayListener(onMediaPlayListener);
            textureViewMini.setOnPtzControlTouchListener(ptzControlTouchListener);
            textureView.setOnPtzControlTouchListener(null);
            mediaSync.setPlayListener(onMiniPlayListener);
        }
    }

    @Override
    public void setSendPTZCmd(boolean isSend) {
        if (isMainPlayer()){
            super.setSendPTZCmd(isSend);
            return;
        }
        textureViewMini.setSendPTZCmd(isSend);

    }

    boolean isOverlapLive(){
        return isPlayLive&&isOpenOverlap;
    }
    boolean isVerticalLive(){
        return isPlayLive&&isVertical();
    }
    boolean isVertical(){
        return !isOpenOverlap;
    }

    boolean isVerticalPlayback(){
        return isVertical()&&!isPlayLive;
    }
    protected abstract int getLayoutID();

    protected abstract int getPiPType();

    interface CameraPlayerPiPType {
        int Overlap = 0, Vertical = 1;
    }

    @Override
    public void anchorViewHide() {
        super.anchorViewHide();
        setPipBtnVisibilityAnimation(GONE);

    }

    @Override
    public void anchorViewShow() {
        super.anchorViewShow();
        if (!isPlayLive||isOverlapLive()||isLandscape()){
            setPipBtnVisibilityAnimation(VISIBLE);
        }
    }

    @Override
    public void playbackResetMin() {
        if (!isVertical()){
            isSdCardPipVideo = false;
            isCloudPipVideo = false;
        }

    }



    private void initMiniVideoOpen() {
        setMiniVideoBtnListener();
        if (mDevice != null) {
            isMiniVideoOpen = PreferenceUtil.getBoolean(mContext, CommonConstants.PRE_PLAYER_VIDEO_MINI_OPEN + mDevice.uuid, true);
            mPipVideoBtn.setSelected(!isMiniVideoOpen);
        }

    }

    protected boolean getPipShowStatus(){

        return  isMiniVideoOpen;
    }

    protected void setPipBtnVisibilityAnimation(int visible) {
        if (isVertical()&&!isLandscape()&&visible==VISIBLE)return;
        if (mPipVideoBtn == null){
            return;
        }
        TGLog.d("ACCameraPlayerView", "visible = " + visible);
        mPipVideoBtn.setSelected(isMiniVideoOpen);
        if (visible == View.VISIBLE) {

            if (isCloudPlayType() && !isCloudPipVideo) {
                return;
            } else if (isSdcardPlayType() && !isSdCardPipVideo) {
                return;
            }
            mPipVideoBtn.animate().translationY(0).setDuration(240).setListener(null).start();
            mSwitchVideoBtn.animate().translationX(0).setDuration(240).setListener(null).start();
            mSwitchVideoBtn.setVisibility(View.VISIBLE);
            mPipVideoBtn.setVisibility(View.VISIBLE);
        } else {
            int w = DimenUtil.dp2px(mContext, 30);
            int top = - ( mPipVideoBtn.getHeight() + w);
            mPipVideoBtn.animate().translationY(top).setDuration(240).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mPipVideoBtn.setVisibility(View.GONE);
                }
            }).start();
            int left = DimenUtil.dp2px(mContext, 15);
            mSwitchVideoBtn.animate().translationX(-(mSwitchVideoBtn.getWidth() + left)).setDuration(240).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mSwitchVideoBtn.setVisibility(View.GONE);
                }
            }).start();
        }
    }

    private void setMiniVideoBtnListener() {
        mPipVideoBtn.setOnClickListener(v -> {
            Object object = TGApplicationBase.getInstance().getGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION);
            if (object instanceof Boolean){
                if ((Boolean)object){
                    return;
                }
            }
            isMiniVideoOpen = !isMiniVideoOpen;
            mPipVideoBtn.setSelected(isMiniVideoOpen);
            if (isMiniVideoOpen) {
                textureView.setVisibility(VISIBLE);
                textureViewMini.setVisibility(VISIBLE);
            } else {
                if (isMainPlayer()) {
                    textureViewMini.setVisibility(GONE);
                    textureViewMini.bringToFront();
                } else {
                    textureView.setVisibility(GONE);
                    textureView.bringToFront();
                }
            }
            if (this instanceof CameraPlayerPiPVerticalView){
                ((CameraPlayerPiPVerticalView)this).bringToFrontZoom(0);
            }
            if (this instanceof CameraPlayerPiPVerticalView){
                ((CameraPlayerPiPVerticalView)this).bringToFrontZoom(1);
            }
            if (mDevice != null) {
                PreferenceUtil.setBoolean(mContext, CommonConstants.PRE_PLAYER_VIDEO_MINI_OPEN + mDevice.uuid, isMiniVideoOpen);
            }
        });

    }

    @Override
    protected void updateMediaType() {
        super.updateMediaType();
        if (mediaSyncMini!=null){
            mediaSyncMini.setPlayType(getMediaType());
        }
    }

    public interface  OnCameraPlayerPiPViewListener{
        void onChanged(int viewId );
    }

}
